from django.shortcuts import render
from django.http import JsonResponse,HttpRequest,HttpResponseRedirect
from .models import User
from .usertool import *
# Create your views here.
def register(request:HttpRequest):
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        try: 
            registerUser(username,password)
        except:
            return render(request,"error.html",{'message':'Failed'})
        return render(request,"error.html",{'message':'Successfully registered'})
    return render(request,'register.html')

def login(request:HttpRequest):
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        try:
            userid=getIDByName(username)
            token=loginUser(userid,password)
        except:
            return render(request,"error.html",{'message':'Failed'})
        respose=render(request,"error.html",{'message':'Successfully logged in<script>window.location.href=\'/\'</script>'})
        respose.set_cookie("session_token",token)
        respose.set_cookie("userid",userid)
        return respose
    return render(request,"login.html")

def logout(request:HttpRequest):
    userid=request.COOKIES.get("userid")
    token=request.COOKIES.get("session_token")
    try:
        logoutUser(userid,token)
    except:
        return render(request,"error.html",{'message':'Failed'})
    response=render(request,"error.html",{'message':'Successfully logged out<a href=\"/\">Back to home</a>'})
    response.delete_cookie("session_token")
    response.delete_cookie("userid")
    return response